package com.hs.hlw.credit.system.web.util;

import com.hs.hlw.credit.system.business.dto.UserDto;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * RequestUtil
 * @author zhb
 * @date 2018/11/20
 */
public class RequestUtil {
    private static final String CC_OWNER_TOKEN = "credit-system-data-collection";
    private static final Map<String, UserCache> USER_CACHE = new ConcurrentHashMap<>();
    private static final Map<String, String> NOT_AUTH_URL = new HashMap<>();

    static {
        NOT_AUTH_URL.put("/api/sys/user/signIn", null);
    }

    /**
     * 获取用户缓存
     * @return
     */
    public static Map<String, UserCache> getUserCache() {
        return USER_CACHE;
    }

    /**
     * 判断不需要鉴权的URL
     * @param url
     * @return
     */
    public static boolean isNotAuthUrl(String url) {
        return NOT_AUTH_URL.containsKey(url);
    }

    /**
     * 从request对象中获取请求参数
     * @param request
     * @return
     */
    public static Map<String, Object> getParamsFromRequest(HttpServletRequest request) {
        Map<String, String[]> params = request.getParameterMap();
        if (params != null && !params.isEmpty()) {
            Map<String, Object> map = new HashMap<>();
            for (String key : params.keySet()) {
                if (params.get(key).length == 1) {
                    map.put(key, params.get(key)[0]);
                } else {
                    map.put(key, params.get(key));
                }
            }
            return map;
        }
        return new HashMap<>();
    }

    /**
     * 保存用户信息
     * @param response
     * @param userDto
     * @return
     */
    public static void saveUserInfo(HttpServletResponse response, UserDto userDto, HttpServletRequest request) {
        String value = UUID.randomUUID().toString();
        Cookie cookie = new Cookie(CC_OWNER_TOKEN, value);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        response.addCookie(cookie);
        response.addHeader(CC_OWNER_TOKEN, value);

        UserCache userCache = new UserCache();
        userCache.setCreateTime(new Date());
        userCache.setUserDto(userDto);
        USER_CACHE.put(value, userCache);
    }

    /**
     * 获取ip地址
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (StringUtils.isNotEmpty(ip) && ip.indexOf(",") != -1) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    /**
     * 删除用户信息
     * @param token
     * @return
     */
    public static void deleteUserInfo(String token) {
        if (USER_CACHE.containsKey(token)) {
            // 获取内存存储
            USER_CACHE.remove(token);
        }
    }

    /**
     * 删除用户信息
     * @param request
     * @return
     */
    public static void deleteUserInfo(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CC_OWNER_TOKEN.equals(cookie.getName())) {
                    deleteUserInfo(cookie.getValue());
                    continue;
                }
            }
        }
    }

    /**
     * 从session中获取用户
     * @param request
     * @return
     */
    public static UserDto getUserFromSession(HttpServletRequest request) {
        UserDto userDto = new UserDto();
        userDto.setId("1");
        userDto.setUserName("超级管理员");
        userDto.setOrgId("1");
        userDto.setOrgName("华龙网");
        return userDto;
    }

    @Data
    public static class UserCache {
        private Date createTime;
        private UserDto userDto;
    }
}
